// pages/evaluation/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animation_class:'',
    animation:'',//题目切换时的动画
    end:false,//是否最后一题
    endchoose:false,//最后一题是否已选
    first:true,//是否第一题
    evaluation: null,
    post_data:{
      subjects:[]
    },
    getnum: 0,
    evaluation_subjects_index:0,
    completed:false,//是否完成测评
    pid:'',
    uuid:'',
    showtreeq:false,
        xpractice:[{
          name:'音频练习',
          id:0,
        path:'/subtool/pages/rudio/index/index'
        }, {
          name: '书写练习',
          id: 1,
          path: '/subtool/pages/dayremb/index/index'
        }, {
          name: '心理测评',
          id: 2,
          path: '/subtool/pages/evaluate/index/index'
        }, {
          name: '小组',
          id: 3,
          path: '/subtool/pages/community/tie/index'
        }],
        xQuestionL:{}
    // progress:0
  },
  onShareAppMessage: function () {
    return {
      title: this.data.evaluation.name
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: async function (options) {
    var that = this;
    if(options.id){
      that.setData({
        pid:options.pid,
        uuid:options.uuid
      })
    }
    that.setData({
      week : options.week
    })
    wx.cloud.callFunction({
      name: 'scale_manage',
      data: {
        action: "get_scale_info",
        return_data_type: 3,
        scale_number: options.id
      }
    }).then(res => {
      console.log(res.result)
      that.setData({
        evaluation: res.result,
        key : options.key
      })
      wx.setNavigationBarTitle({
          title: res.result.name,
          success: (res) => {},
          fail: (res) => {},
          complete: (res) => {},
      })
      let subject_numbers = res.result.subjects.length
      let getnum = 0
      let allq = res.result.subjects
      for(var i in allq){
        getnum += allq[i].options.length - 1
      }
      console.log(getnum)
      that.setData({
        getnum : getnum 
      })
      if (that.data.evaluation_subjects_index + 1 >= subject_numbers) {
        that.setData({
          end: true ,
        });
      }
    })
    // if(options.key === 'other'){
    //   wx.cloud.callFunction({
    //     name: 'scale_manage',
    //     data: {
    //       action: "get_scale_info",
    //       return_data_type: 3,
    //       scale_number: options.id
    //     }
    //   }).then(res => {
    //     console.log(res)
    //     that.setData({
    //       evaluation: res.result,
    //       key : options.key
    //     })
    //     let subject_numbers = res.result.subjects.length
    //     if (that.data.evaluation_subjects_index + 1 >= subject_numbers) {
    //       that.setData({
    //         end: true
    //       });
    //     }
    //   })
    // }else{
    //   this.setData({
    //     options:options
    //   });
    //   var evaluation_id = options.id;
    //   var second_flag = options.second_flag;
    //   if(second_flag == undefined){
    //     second_flag = 0
    //   }
    //   wx.showLoading({
    //     title: '加载中...',
    //   })
    //   var res = await wx.cloud.callFunction({
    //     name: "evaluation",
    //     data: {
    //       action: "detail_answer",
    //       id: evaluation_id,
    //       second_flag: second_flag
    //     }
    //   })
    //   wx.hideLoading();
    //   res.result.subject_numbers = res.result.subjects.length
    //   this.setData({
    //     evaluation: res.result
    //   })
    //   wx.setNavigationBarTitle({
    //     title: that.data.evaluation.name
    //   })
    //   if (that.data.evaluation_subjects_index + 1 >= that.data.evaluation.subject_numbers) {
    //     that.setData({
    //       end: true
    //     });
    //   }
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.animationfunc();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  // onShow: function () {
  //   if (!app.checklogin_filter()) {//用户登陆拦截器，判断用户是否登陆
  //     return false;
  //   }
  // },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // if(!this.data.completed){
    //   wx.showModal({
    //     title: '提醒',
    //     content: '退出后，已选答案不保留',
    //     showCancel: false
    //   })
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //  tool
  xToInfortool: function (e) {
    let path = e.currentTarget.dataset.path
    wx.navigateTo({
      url: path,
    })
  },
  showtreeqh : function ( ){
    wx.switchTab({
      url: '../../../../pages/navigation/index/index',
    })
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  //题目切换时的动画
  animationfunc:function(){
    var animation = wx.createAnimation({
      duration:2000,
      timingFunction:'ease'
    })
    // animation.translateX(375).step()
    // animation.translateX(0).step()
    animation.opacity(1).step();
    this.setData({
      //输出动画
      animation: animation.export()
    })
  },
  optionChange:function(event){
    let that = this;
    var evaluation_subjects_index = that.data.evaluation_subjects_index; // 0
    if (that.data.first) {
      that.setData({
        first: false
      })
    }
    var tmpsss_subject = that.data.evaluation.subjects[evaluation_subjects_index];
    var options = tmpsss_subject.options;
    var selectedOptionId = event.currentTarget.dataset.id; //获取当前选中的选项
    for (const x in options) {
      //获取当前选中的选项
      if (options[x].id == selectedOptionId) {
        options[x].checked = true;
        //设置表单提交的数据
        var post_data = that.data.post_data;
        let okey = that.data.key
        if(okey === 'other'){
          post_data.subjects[evaluation_subjects_index] = {
            name: tmpsss_subject.name,
            options: options
          }
        }else{
          post_data.subjects[evaluation_subjects_index] = {
            // subject_id: tmpsss_subject._id,
            subject_name: tmpsss_subject.name,
            // subject_type: tmpsss_subject.type,
            // scales_id: tmpsss_subject.scales_id,
            answer_option: options[x].name,
            answer_score:options[x].score,
          }
        }
        //设置表单提交的数据
        that.setData({
          post_data:post_data
        })
        //设置表单提交的数据
      } else {
        options[x].checked = false;
      }
    }
    let tmp_evaluation = that.data.evaluation;
    tmp_evaluation.subjects[evaluation_subjects_index].options = options;
    that.setData({
      evaluation: tmp_evaluation,
    })
    if(that.data.end){//已经是最后一题
      //设置最后一题已选
      that.setData({
        endchoose: true
      });
      return false;
    }

    var next_index = evaluation_subjects_index + 1;
    if(that.data.evaluation.subject_numbers === undefined){
      if (next_index+1 >= that.data.evaluation.subjects.length) {
        that.setData({
          end: true
        });
      }
    }else{
      if (next_index+1 >= that.data.evaluation.subject_numbers) {
        that.setData({
          end: true
        });
      }
    }

    setTimeout(function () {
      that.setData({
        evaluation_subjects_index: next_index //下一题
      })
      //切换动画
      that.setData({
        animation_class: 'animation_class'
      })
    }, 300); 

    // that.setData({
    //   evaluation_subjects_index: next_index //下一题
    // })
    
    

  },
  aniamtionend:function(){
    this.setData({
      animation_class: ''
    })
  },
  // nextSubject:function(){

  // },
  preFunc:function(){//上一题
    let that = this;
    var evaluation_subjects_index = that.data.evaluation_subjects_index;
    var pre_index = evaluation_subjects_index - 1;
    if (pre_index <= 0) {
      pre_index = 0;
      that.setData({
        first: true
      });
      if (that.data.evaluation.subject_numbers>1){//若总题目数大于1，则就不可能既是第一题又是最后一题
        that.setData({
          end: false,
          endchoose: false
        });
      }
    }else{
      that.setData({
        first: false,
        end:false,
        endchoose:false
      });
    }
    //删除当前这题的答案
    var post_data = that.data.post_data;
    post_data.subjects.pop();
    that.setData({
      post_data:post_data
    })
    // -- 删除当前这题的答题记录
    var options = that.data.evaluation.subjects[evaluation_subjects_index].options;
    for(var k=0;k<options.length;++k){
      options[k].checked = false;
    }
    let tmp_evaluation = that.data.evaluation;
    tmp_evaluation.subjects[evaluation_subjects_index].options = options;
    that.setData({
      evaluation: tmp_evaluation,
    })
    // -- 删除当前这题的答题记录

    setTimeout(function () {
      that.setData({
        evaluation_subjects_index: pre_index //上一题
      })
    //切换动画
    that.setData({
      animation_class: 'pre_animation_class'
    })
    }, 300); 
  },
  submitFunc:function(res){
    let that = this;
    let eva = that.data.evaluation
    let okey = that.data.key
    console.log(eva)
    var post_data = that.data.post_data;
    if(post_data.subjects.length < that.data.evaluation.subject_numbers ){
      wx.showToast({
        title: '请测评完所有题目',
        icon:"none",
        duration:1000
      })
      return false;
    }
    //发送提交测评的请求
    let xData = {}
    // if(okey === 'other'){
    //   xData = {
    //     _id: eva._id,
    //     name: eva.name,
    //     name_other: eva.name_other,
    //     type: eva.type,
    //     name_en: eva.name_en,
    //     scale_number: eva.scale_number,
    //     desc: eva.desc,
    //     subjects: post_data.subjects ,
    //     results_assessment: eva.results_assessment ,
    //     week : that.data.week
    //   }
    // }
    xData = {
      _id: eva._id,
      name: eva.name,
      name_other: eva.name_other,
      type: eva.type,
      name_en: eva.name_en,
      scale_number: eva.scale_number,
      desc: eva.desc,
      subjects: post_data.subjects ,
      results_assessment: eva.results_assessment ,
      week : that.data.week
    }
    console.log(xData)
    let xRes = 0
    for(var i in xData.subjects){
      let opt = xData.subjects[i].answer_score
      if(opt > 0){
        xRes += opt
      }
    }
    let uploadres = {}
    for(var o in xData.results_assessment){
      if(xRes >= xData.results_assessment[o].min_score && xData.results_assessment[o].max_score >= xRes){
        uploadres = {
          results_assessment : xData.results_assessment[o] ,
          score : xRes
        }
      }
    }
    console.log('得分' , xRes , '结果' , uploadres)
    console.log(xData , uploadres)
    post_data.evaluation = that.data.evaluation;
    delete post_data.evaluation.subjects;
    console.log(post_data);
    wx.showLoading({
      title: '提交数据......',
    })
    wx.cloud.callFunction({
      name: 'scale_manage',
      data: {
          action: "add_scale_return_by_user",
          dataObj:{
            answer_results : xData ,
            test_results : uploadres
          }
      }
    }).then(res => {
      let state = res.result
      let allnum = that.data.getnum
      if(state){
        wx.hideLoading();
          that.setData({ completed:true});
          wx.redirectTo({
            url: '/subtool/pages/evaluate/eva-ays/index?score=' + uploadres.score + '&assessment=' + uploadres.results_assessment.desc + '&state=' + uploadres.results_assessment.name + '&name=' + xData.name + '&num=' + allnum + '&id=' + xData.scale_number ,
          })
      }else{
        wx.showModal({
          title : '错误',
          icon : 'none'
        })
      }
    })
    // if(okey === 'other'){
    //   wx.cloud.callFunction({
    //     name: 'scale_manage',
    //     data: {
    //         action: "add_scale_return_by_user",
    //         dataObj:{
    //           answer_results : xData ,
    //           test_results : uploadres
    //         }
    //     }
    //   }).then(res => {
    //     let state = res.result
    //     if(state){
    //       wx.hideLoading();
    //       that.setData({ completed:true});
    //       wx.redirectTo({
    //         url: '/subtool/pages/evaluate/eva-ays/index'
    //       })
    //     }else{
    //       wx.showModal({
    //         title : '错误',
    //         icon : 'none'
    //       })
    //     }
    //   })
    // }else{
    //   wx.cloud.callFunction({
    //     name:"evaluation",
    //     data:{
    //       action: "user_add",
    //       post_data: post_data,
    //       extradata:{
    //         plan_user_id:that.data.options.plan_user_id,
    //         plan_user_code:that.data.options.code,
    //         week : that.data.week
    //       },
    //     },
    //     success:function(res){
    //       var evaluation_user_id = res.result._id;
    //       wx.hideLoading();
    //       that.setData({ completed:true});
    //       if(!res.result.success){
    //         wx.showModal({
    //           title:'错误',
    //           content:res.result.msg,
    //           showCancel:false
    //         })
    //         return false;
    //       }
    //       wx.redirectTo({
    //         url: '/subtool/pages/evaluate/eva-ays/index?id=' + evaluation_user_id,
    //       })
    //     }
    //   })
    // }
  }
})